package com.example.idachuappone.cook.item;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.example.idachuappone.BaseActivity;
import com.example.idachuappone.LoadingActivity;
import com.example.idachuappone.R;
import com.example.idachuappone.index.dialog.DialogDateHours;
import com.example.idachuappone.index.dialog.DialogPackage;
import com.example.idachuappone.index.dialog.DialogPackage.CallBack;
import com.example.idachuappone.index.dto.WelcomeDto;
import com.example.idachuappone.index.entity.DateTime;
import com.example.idachuappone.index.welcomentity.Packages;
import com.example.idachuappone.person.entity.Order;
import com.example.idachuappone.person.item.LoginActivity;
import com.example.idachuappone.promptly.entity.Addresses;
import com.example.idachuappone.promptly.item.CookAddressListActivity;
import com.example.idachuappone.utils.ComUtil;
import com.example.idachuappone.utils.Constant;
import com.example.idachuappone.utils.CusProSmallBgDialog;
import com.example.idachuappone.utils.MainToast;
import com.example.idachuappone.utils.NetUtil;
import com.example.idachuappone.utils.PrefUtil;
import com.lidroid.xutils.bitmap.BitmapGlobalConfig.BitmapCacheManagementTask;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

public class PrompTwoCookActivity extends BaseActivity implements OnCheckedChangeListener, OnClickListener {
	private int addressRequestCode;
	private Addresses addresses;
	private Button btn_back;
	private Button btn_submit;
	private CusProSmallBgDialog cusProDialog;
	private String detailTimeFormat;
	private Dialog dialogLoading;
	private Dialog dialogPackages;
	private Dialog dialogTime;
	private EditText et_desc;
	private int ingredient;
	private boolean isNoAddress;
	private LinearLayout ll_address;
	private LinearLayout ll_address_gone;
	private LinearLayout ll_address_visible;
	private LinearLayout ll_package;
	private LinearLayout ll_package_gone;
	private LinearLayout ll_package_visible;
	private LinearLayout ll_time;
	private LinearLayout ll_time_gone;
	private LinearLayout ll_time_visible;
	private int loginRequest;
	private Packages packagesub;
	private RadioGroup rg_isfood;
	private TextView tv_day;
	private TextView tv_desc;
	private TextView tv_hour_min;
	private TextView tv_packages;
	private TextView tv_user_address;
	private TextView tv_user_name;
	private TextView tv_user_phone;
	private TextView tv_year_mon_day;

	public PrompTwoCookActivity() {
		this.ingredient = 0;
		this.addressRequestCode = 15;
		this.loginRequest = 255;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_promp_two_cook);
		this.cusProDialog = new CusProSmallBgDialog(this);
		this.dialogLoading = ComUtil.createCusProgressSmallBlackBgDialog(this);
		initView();
		initDateTime(this);
		initPackageData();
	}

	private void initView() {
		this.rg_isfood = (RadioGroup) findViewById(R.id.rg_isfood);
		this.rg_isfood.setOnCheckedChangeListener(this);
		this.btn_back = (Button) findViewById(R.id.btn_back);
		this.btn_back.setOnClickListener(this);
		this.btn_submit = (Button) findViewById(R.id.btn_submit);
		this.btn_submit.setOnClickListener(this);
		this.ll_time = (LinearLayout) findViewById(R.id.ll_time);
		this.ll_time.setOnClickListener(this);
		this.ll_time_gone = (LinearLayout) findViewById(R.id.ll_time_gone);
		this.ll_time_visible = (LinearLayout) findViewById(R.id.ll_time_visible);
		this.tv_day = (TextView) findViewById(R.id.tv_day);
		this.tv_year_mon_day = (TextView) findViewById(R.id.tv_year_mon_day);
		this.tv_hour_min = (TextView) findViewById(R.id.tv_hour_min);
		this.ll_address = (LinearLayout) findViewById(R.id.ll_address);
		this.ll_address.setOnClickListener(this);
		this.ll_address_gone = (LinearLayout) findViewById(R.id.ll_address_gone);
		this.ll_address_visible = (LinearLayout) findViewById(R.id.ll_address_visible);
		this.tv_user_name = (TextView) findViewById(R.id.tv_user_name);
		this.tv_user_phone = (TextView) findViewById(R.id.tv_user_phone);
		this.tv_user_address = (TextView) findViewById(R.id.tv_user_address);
		initAddress();
		this.tv_desc = (TextView) findViewById(R.id.tv_desc);
		this.et_desc = (EditText) findViewById(R.id.et_desc);
		this.et_desc.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					PrompTwoCookActivity.this.tv_desc
							.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
				}
			}
		});
		this.et_desc.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (PrompTwoCookActivity.this.et_desc.getText().toString().length() >= 100) {
					MainToast.show(PrompTwoCookActivity.this, "\u5907\u6ce8\u6700\u591a\u53ef\u8f93\u5165100\u5b57", 0);
				}
			}
		});
		this.ll_package = (LinearLayout) findViewById(R.id.ll_package);
		this.ll_package.setOnClickListener(this);
		this.ll_package_gone = (LinearLayout) findViewById(R.id.ll_package_gone);
		this.ll_package_visible = (LinearLayout) findViewById(R.id.ll_package_visible);
		this.tv_packages = (TextView) findViewById(R.id.tv_packages);
	}

	private void initAddress() {
		PrefUtil pp = PrefUtil.getInstance(this);
		if (pp.getXiaoQu() == null || pp.getXiaoQu().length() <= 0) {
			this.isNoAddress = true;
			this.ll_address_gone.setVisibility(0);
			this.ll_address_visible.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
			return;
		}
		this.isNoAddress = false;
		this.ll_address_gone.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
		this.ll_address_visible.setVisibility(0);
		this.addresses = new Addresses(pp.getUserAddressId(), "", pp.getName(), pp.getPhone(), pp.getArea(),
				pp.getXiaoQu(), pp.getDoor(), "", "");
		setAddress(this.addresses);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (this.isNoAddress) {
			initAddress();
		}
	}

	private void setAddress(Addresses addresses) {
		this.ll_address_gone.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
		this.ll_address_visible.setVisibility(0);
		this.tv_user_name.setText(addresses.getName());
		this.tv_user_phone.setText(addresses.getPhone());
		this.tv_user_address.setText(addresses.getCommunity() + addresses.getDoor_number());
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch (checkedId) {
		case R.id.rbtn_false /* 2131165279 */:
			this.ingredient = 1;
		case R.id.rbtn_true /* 2131165280 */:
			this.ingredient = 0;
		default:
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back /* 2131165198 */:
			finish();
		case R.id.ll_address /* 2131165259 */:
			if (PrefUtil.getInstance(this).getUID() == null) {
				MainToast.show(this, "\u60a8\u8fd8\u6ca1\u6709\u767b\u5f55\uff0c\u8bf7\u5148\u767b\u5f55", 0);
				startActivityForResult(new Intent(this, LoginActivity.class), this.loginRequest);
				return;
			}
			Intent intent = new Intent(this, CookAddressListActivity.class);
			if (this.addresses != null) {
				intent.putExtra("userAddressId", this.addresses.getId());
			}
			startActivityForResult(intent, this.addressRequestCode);
		case R.id.ll_time /* 2131165265 */:
			this.dialogTime.show();
		case R.id.ll_package /* 2131165271 */:
			this.dialogPackages.show();
		case R.id.btn_submit /* 2131165282 */:
			if (PrefUtil.getInstance(this).getUID() == null) {
				MainToast.show(this, "\u60a8\u8fd8\u6ca1\u6709\u767b\u5f55\uff0c\u8bf7\u5148\u767b\u5f55", 0);
				startActivityForResult(new Intent(this, LoginActivity.class), 22);
			} else if (this.addresses == null) {
				MainToast.show(this, "\u8bf7\u5b8c\u5584\u5730\u5740\u4fe1\u606f", 0);
			} else if (this.detailTimeFormat == null || this.detailTimeFormat.length() == 0) {
				MainToast.show(this, "\u8bf7\u9009\u62e9\u65f6\u95f4", 1);
			} else if (this.packagesub == null) {
				MainToast.show(this, "\u8bf7\u5b8c\u5584\u5957\u9910\u4fe1\u606f", 0);
			} else {
				this.btn_submit.setEnabled(false);
				Map<String, String> map = new HashMap();
				map.put("date", this.detailTimeFormat);
				map.put("package",
						new StringBuilder(String.valueOf(this.packagesub.getId())).append("-")
								.append(this.packagesub.getPrice()).toString());
				map.put("area", this.addresses.getArea());
				map.put("community", this.addresses.getCommunity());
				map.put("door_number", this.addresses.getDoor_number());
				map.put("name", this.addresses.getName());
				map.put("kitchener_id", "");
				map.put("phone", this.addresses.getPhone());
				map.put("ver", "2");
				map.put("memo", this.et_desc.getText().toString());
				map.put("ingredient", new StringBuilder(String.valueOf(this.ingredient)).toString());
				map.put("app", "2");
				NetUtil.post(this, Constant.PROMPTLY, map, new RequestCallBack<String>() {
					@Override
					public void onStart() {
						super.onStart();
						PrompTwoCookActivity.this.cusProDialog.setMsg("\u63d0\u4ea4\u8ba2\u5355\u4e2d...");
						PrompTwoCookActivity.this.cusProDialog.show();
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						PrompTwoCookActivity.this.cusProDialog.dismiss();
						try {
							JSONObject jsonObject = new JSONObject(NetUtil.unescapeUnicode(responseInfo.result));
							if (jsonObject.getInt("code") == 10000) {
								Intent intent = new Intent(PrompTwoCookActivity.this, PayPromptlyActivity.class);
								intent.putExtra("isprom", true);
								intent.putExtra("isorder", false);
								intent.putExtra("orderid", new Order().parseJson(jsonObject.getJSONObject("data"))
										.getId());
								PrompTwoCookActivity.this.startActivity(intent);
								return;
							}
							MainToast.show(PrompTwoCookActivity.this, jsonObject.getString("error"), 0);
							PrompTwoCookActivity.this.btn_submit.setEnabled(true);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						PrompTwoCookActivity.this.cusProDialog.dismiss();
						PrompTwoCookActivity.this.btn_submit.setEnabled(true);
						MainToast.show(PrompTwoCookActivity.this,
								PrompTwoCookActivity.this.getResources().getString(R.string.netFail), 0);
					}
				});
			}
		default:
		}
	}

	private void showPackageDialog(List<Packages> packages) {
		this.dialogPackages = new DialogPackage(packages, this).showPackageDialog(this, new CallBack() {
			@Override
			public void btnOk(Packages packages) {
				PrompTwoCookActivity.this.packagesub = packages;
				PrompTwoCookActivity.this.ll_package_gone
						.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
				PrompTwoCookActivity.this.ll_package_visible.setVisibility(0);
				if (Integer.parseInt(packages.getPrice()) == 0) {
					PrompTwoCookActivity.this.tv_packages.setText(packages.getName());
				} else {
					PrompTwoCookActivity.this.tv_packages.setText(packages.getName() + "/" + packages.getPrice()
							+ "\u5143(" + packages.getDescription() + ")");
				}
				PrompTwoCookActivity.this.dialogPackages.dismiss();
			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == this.addressRequestCode && resultCode == -1) {
			this.addresses = (Addresses) data.getExtras().getSerializable("address");
			setAddress(this.addresses);
		}
		if (requestCode == this.loginRequest && resultCode == -1) {
			initAddress();
		}
	}

	private void initPackageData() {
		if (LoadingActivity.welcome.getPackages() == null || LoadingActivity.welcome.getPackages().size() <= 0) {
			this.dialogLoading.show();
			NetUtil.get(this, Constant.PACKAGES, 100, new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					PrompTwoCookActivity.this.dialogLoading.dismiss();
					try {
						LoadingActivity.welcome = new WelcomeDto().getWelcome(PrompTwoCookActivity.this,
								NetUtil.unescapeUnicode(responseInfo.result));
						PrompTwoCookActivity.this.showPackageDialog(LoadingActivity.welcome.getPackages());
					} catch (Exception e) {
						MainToast.show(PrompTwoCookActivity.this, e.getMessage(), 0);
					}
				}

				@Override
				public void onFailure(HttpException arg0, String arg1) {
					NetUtil.netFail(PrompTwoCookActivity.this, PrompTwoCookActivity.this.dialogLoading, true);
				}
			});
			return;
		}
		showPackageDialog(LoadingActivity.welcome.getPackages());
	}

	private void initDateTime(Context context) {
		this.dialogTime = new DialogDateHours(context).showDateHours(this, new DialogDateHours.CallBack() {
			@Override
			public void btnOk(DateTime dateTime, int hourindex, String min) {
				PrompTwoCookActivity.this.detailTimeFormat = ComUtil.FormatCalenderTime3(dateTime.getYearnum()
						+ "\u5e74" + (dateTime.getYear() + " " + (dateTime.getList().get(hourindex)) + ":" + min));
				PrompTwoCookActivity.this.ll_time_gone
						.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
				PrompTwoCookActivity.this.ll_time_visible.setVisibility(0);
				if (dateTime.getDay() == null || dateTime.getDay().length() <= 0) {
					PrompTwoCookActivity.this.tv_day
							.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
				} else {
					PrompTwoCookActivity.this.tv_day.setVisibility(0);
					PrompTwoCookActivity.this.tv_day.setText(dateTime.getDay());
				}
				PrompTwoCookActivity.this.tv_year_mon_day.setText(dateTime.getYear());
				PrompTwoCookActivity.this.tv_hour_min.setText(new StringBuilder(String.valueOf(dateTime.getList().get(
						hourindex))).append(":").append(min).toString());
				PrompTwoCookActivity.this.dialogTime.dismiss();
			}
		});
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (ev.getAction() == 0) {
			View v = getCurrentFocus();
			if (isShouldHideInput(v, ev)) {
				hideSoftInput(v.getWindowToken());
			}
		}
		return super.dispatchTouchEvent(ev);
	}

	private boolean isShouldHideInput(View v, MotionEvent event) {
		if (v == null || !(v instanceof EditText)) {
			return false;
		}
		int[] l = new int[2];
		v.getLocationInWindow(l);
		int left = l[0];
		int top = l[1];
		return event.getX() <= (left) || event.getX() >= (left + v.getWidth()) || event.getY() <= (top)
				|| event.getY() >= (top + v.getHeight());
	}

	private void hideSoftInput(IBinder token) {
		if (token != null) {
			((InputMethodManager) getSystemService("input_method")).hideSoftInputFromWindow(token,
					BitmapCacheManagementTask.MESSAGE_FLUSH);
			if (this.et_desc.getText().toString().trim().length() == 0) {
				this.tv_desc.setVisibility(0);
			}
			this.et_desc.clearFocus();
		}
	}
}
